package com.zhenzhang.myblog.controller;

import com.zhenzhang.myblog.exception.JsonException;
import com.zhenzhang.myblog.utils.JsonResult;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

// SpringBoot运行的时候如果出现异常没被try..catch，就会转来这里对应的方法
@RestControllerAdvice
public class ControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult argsErr(MethodArgumentNotValidException err, HttpServletResponse response) {
        StringBuffer sb = new StringBuffer();
        err.getBindingResult().getFieldErrors().forEach(e -> {
            sb.append(e.getField()).append(": ").append(e.getDefaultMessage()).append(';');
        });
        response.setStatus(422);
        return JsonResult.getInstance(422, sb.toString());
    }

    // 捕获键值冲突异常
    @ExceptionHandler(DuplicateKeyException.class)
    public JsonResult duplicateKey(HttpServletResponse response) {
        response.setStatus(422);
        return JsonResult.getInstance(422, "用户已被使用");
    }

    @ExceptionHandler(TooManyResultsException.class)
    public JsonResult tooManyResults(HttpServletResponse response) {
        response.setStatus(422);
        return JsonResult.getInstance(422,"不能使用重复标题，请更换标题");
    }

    // 手动抛出我们自定义的一个异常，然后在这里处理，最终HTTP响应码设置为对应的JsonResult的code
    @ExceptionHandler(JsonException.class)
    public JsonResult jsonException(JsonException e, HttpServletResponse response) {
        response.setStatus(e.getResult().getCode());
        return e.getResult();
    }
}
